import { message } from "antd";
import axios,{AxiosResponse,Method,ResponseType,AxiosRequestConfig,AxiosError} from 'axios'
import { store } from '@/redux/index'

const http = axios.create({
    baseURL: 'http://localhost:3300',
    timeout: 10000,
});

// axios request 拦截器
http.interceptors.request.use((config) => {
        //判断token是否存在
        const token = store.getState().global.token;
        if(token){
            config.headers.Authorization = `Bearer ${token}`
        }
        return config
    },
    (error: AxiosError) => {
        return Promise.reject(error)
    }
)
// http response 拦截器
http.interceptors.response.use((response) => {
    let code = response.data.code
    let msg = response.data.message
    if(response.status === 200){
        if(code == 0){
            return Promise.resolve(response.data);
        }else{
            message.warning(msg);
        }
    }else{
        message.error(msg || '操作失败！');
        return Promise.reject(response)
    }
}, (error: AxiosError) => {
    let status = error.response.status
    if(status == '403'){
        window.location.href = '/login';
        return false
    }else{
        message.error(error.response.data.message || '操作失败！');
        return Promise.reject(error)
    }
})

export default  http;
